package handlers

import (
	"github.com/gin-gonic/gin"
	"perm-sys/models"
	"perm-sys/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user.Password,
	})
	return
}

func Role(c *gin.Context) {
	user_id, _ := strconv.Atoi(c.PostForm("user_id"))
	rolename := c.PostForm("rolename")

	tx := models.DB.Begin()
	role := models.Role{
		UserID:   user_id,
		RoleName: rolename,
	}
	err := tx.Preload("User").Create(&role).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "分配角色失败",
		})
		return
	} else {
		tx.Commit()
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "分配角色成功",
		})
		return
	}
}

func Power(c *gin.Context) {
	role_id, _ := strconv.Atoi(c.PostForm("role_id"))
	powername := c.PostForm("powername")
	tx := models.DB.Begin()
	power := models.Power{
		RoleID:    role_id,
		PowerName: powername,
	}
	err := tx.Preload("User").Create(&power).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "分配权力失败",
		})
		return
	} else {
		tx.Commit()
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "分配权力成功",
		})
		return
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "1"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.User{}).Count(&count)

	var user []models.User
	err := models.DB.Offset(offset).Limit(size).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询错误",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": gin.H{
				"count": count,
				"user":  user,
			},
		})
		return
	}
}
